package org.ttitfly.ttcore.system;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.stereotype.Component;
import org.ttitfly.ttcore.entity.account.Role;
import org.ttitfly.ttcore.entity.account.User;
import org.ttitfly.ttcore.entity.menu.SystemMenu;
import org.ttitfly.ttcore.service.account.RoleManager;
import org.ttitfly.ttcore.service.account.UserManager;
import org.ttitfly.ttcore.service.menu.SystemMenuManager;


/**
 * 系统基础数据初始化方法
 * @author: mahaibo
 */
@Component
public class InitSystem {
	
	public static final String BEAN_ID = "initSystem";
	
	private SystemMenuManager systemMenuMgr = (SystemMenuManager) Platform.getInstance().getBean("systemMenuManager");
	private UserManager userMgr = (UserManager) Platform.getInstance().getBean("userManager");
	private RoleManager mgrRole = (RoleManager)Platform.getInstance().getBean("roleManager");
	
	private List<SystemMenu> systemMenuList = new ArrayList<SystemMenu>();
	private List<Role> roleList = new ArrayList<Role>();
	
	/**
	 * 系统初始化方法，仅当初始化密码与配置文件相同，并且管理员不存在，方可初始化
	 * 
	 * @param password   初始化密码
	 */
	public void doInit(String password) {
		
		// 必须提供密码方可执行
		if (StringUtils.isNotBlank(password)) {
			if (password.equals("123456")) {
				// 以下信息不能重复创建，因此检索数据库中是否含有admin用户
				if (userMgr.findUserByLoginname("admin") == null) {
					saveSystemMenu();//菜单
					saveRole();//角色
					saveUser();//用户
					
				}
			}
		}
	}

	/**
	 * 初始化用户
	 */
	private void saveUser() {
		User user = createUser("admin", "admin");
		user.setRoles(roleList);
		userMgr.saveUser(user);
	}
	
	/**
	 * 初始化角色
	 */
	private void saveRole(){
		Role role = createRole("管理员");
		role.setMenus(systemMenuList);
		mgrRole.saveRole(role);
		roleList.add(role);
	}
	
	/**
	 * 初始化菜单
	 */
	private void saveSystemMenu() {
		String ctx = Platform.getInstance().getWebPath();
		String path = ctx + "/WEB-INF/classes/config/init-menu.xml";
		try {
			Document document = new SAXReader().read(path);
			importSystemMenu(document.selectNodes("menus/menu"), 0);
		} catch (DocumentException e) {
			e.printStackTrace();
		}
	}
	
	
	

	private User createUser(String username, String password) {
		User obj = new User();
		obj.setName(username);
		obj.setLoginName(username);
		obj.setPassword(password);
		obj.setEmail("admin@163.com");
		return obj;
	}
	
	private Role createRole (String name){
		Role role = new Role();
		role.setName(name);
		return role;
	}
	
	
	
	private long count = 0;//id
    @SuppressWarnings("unchecked")
	public void importSystemMenu(List menus, long parentId){
    	//int onum = 0;
    	for (Object object : menus) {
    		count ++ ;
			Element element = (Element)object;
			SystemMenu systemMenu = new SystemMenu();
//			systemMenu.setId(count);
			systemMenu.setTitle(element.attributeValue("title"));
			systemMenu.setUrl(element.attributeValue("url"));
			systemMenu.setKeyword(element.attributeValue("keyword"));
			systemMenu.setLeaf(Integer.parseInt(element.attributeValue("leaf")));
			systemMenu.setParentId(parentId);
			//systemMenu.setOrderNum(onum++);
			systemMenu.setOrderNum(Integer.parseInt(element.attributeValue("orderNum")));
			systemMenu.setStyle(element.attributeValue("style"));
			systemMenuMgr.saveOrUpdate(systemMenu);
			systemMenuList.add(systemMenu);
			List children = element.selectNodes("menu");
			
			if(children.size()!=0){
				importSystemMenu(children,systemMenu.getId());
			}
		}
    }

	

}
